//
// Created by haoy on 2017/6/30.
//

#ifndef MERGE_FILE_BUF_HPP
#define MERGE_FILE_BUF_HPP

#include <streambuf>

class fp_buf : public std::streambuf {
public:
    fp_buf(FILE* fp): fp_(fp) {}
    int underflow() {
        if (this->gptr() == this->egptr()) {
            int size = fread(this->buffer_, 1, buffer_size, this->fp_);
            if (0 < size) {
                this->setg(this->buffer_, this->buffer_, this->buffer_ + size);
            }
        }
        return this->gptr() == this->egptr()
               ? traits_type::eof()
               : traits_type::to_int_type(*gptr());
    }

    ~fp_buf() {
        if (fp_) {
            pclose(fp_);
            fp_ = nullptr;
        }
    }
private:
    FILE* fp_;
    static constexpr int buffer_size = 1024;
    char buffer_[buffer_size];
};


#endif //MERGE_FILE_BUF_HPP
